  // pages/biz/wallet/openWallet/openWallet.js
import Serv from './openWalletSer.js'

var event = require('../../../../utils/event.js')
import util from '../../../../utils/util2'
import config from '../../../../utils/config2'
console.log('config',config)
var regeneratorRuntime = require('../../../../lib/js/runtime-module.js')

let TimerClass = util.TimerClass

// 公务员 事业单位员工  企业高管 私营业主  金融从业人员 律师  会计师  医护人员 学生 公司员工 商业服务  工人  农林牧副渔   军人武警 文体工作者  家庭主妇 退休 自由职业者  其他  司机
let OccupationList = [
  {
    id: '01',
    name: '公务员',
  },
  {
    id: '02',
    name: '事业单位员工',
  },
  {
    id: '03',
    name: '企业高管',
  },
  {
    id: '04',
    name: '私营业主',
  },
  {
    id: '05',
    name: '金融从业人员',
  },
  {
    id: '06',
    name: '律师',
  },
  {
    id: '07',
    name: '会计师',
  },
  {
    id: '08',
    name: '医护人员',
  },
  {
    id: '09',
    name: '学生',
  },
  {
    id: '10',
    name: '公司员工',
  },
  {
    id: '11',
    name: '商业服务',
  },
  {
    id: '12',
    name: '工人',
  },
  {
    id: '13',
    name: '农林牧副渔',
  },
  {
    id: '14',
    name: '军人武警',
  },
  {
    id: '15',
    name: '文体工作者',
  },
  {
    id: '16',
    name: '家庭主妇',
  },
  {
    id: '17',
    name: '退休',
  },
  {
    id: '18',
    name: '自由职业者',
  },
  {
    id: '19',
    name: '其他',
  },
  {
    id: '20',
    name: '司机',
  },
]

let timerObj = null//计时器实例

Page({
  
  /**
   * 页面的初始数据
   */
  data: {
    imgUrls: [
      'http://img02.tooopen.com/images/20150928/tooopen_sy_143912755726.jpg',
      'http://img06.tooopen.com/images/20160818/tooopen_sy_175866434296.jpg',
      'http://img06.tooopen.com/images/20160818/tooopen_sy_175833047715.jpg'
    ],
    bankList: [],
    OccupationList: OccupationList,
    
    // 进行的步骤
    step: 1,
    disabled: false,
    isSendMsg: false,
    countText: '发送验证码',
    token: '',//从获取验证码接口取到的token
    timeCount: 0,
    showBankList: true,
    showOccupationList: true,

    // 表单
    occupationIndex: '19',
    bankIndex: '',
    curBankItem: {},
    curOccupationItem: OccupationList[19],
    occupation: OccupationList[19]['id'],//职业编码
    linked_acctno: '',//银行卡号
    user_name: '',
    id_no: '',
    reg_phone: '',
    
    // 密码随机因子
    password: {},
    password_new: {},
    random_key: '',
    
    // 验证码
    verify_code: '',
    inputDisable: false,
    cardNoState:false
  },
  
  // 显示银行列表
  showBank () {
    this.setData({showBankList: false})
  },
  
  // 隐藏银行列表
  hideBank () {
    this.setData({showBankList: true})
  },
  showOccupation () {
    this.setData({showOccupationList: false})
  },
  hideOccupation () {
    this.setData({showOccupationList: true})
  },
  // 发送验证码
  sendMsg: async function () {
    let {user_name, id_no, bankIndex, occupationIndex, linked_acctno, reg_phone, verify_code, user_id, password, open_flag, curOccupationItem, timeCount, disabled, countText, isSendMsg,curBankItem,cardNoState} = this.data
    let phone = wx.getStorageSync(config.phoneNoKey)||''
    // 验证码传参
    let params = {
      user_id: user_id,
      open_flag: open_flag,
      bank_code:curBankItem.bank_code,
      basicInfo: {
        reg_phone:phone,
        user_name,
        id_type: 'ID_CARD',
        id_no,
        id_exp: '99991231',
        address: '',
        occupation: curOccupationItem.id
      },
      linkedAcctInfo: {
        linked_acctno,
        linked_phone: reg_phone,
        cvv2: '',
        valid_thru: ''
      }
    }
    // 校验表单
    let regMag = {
      mobile: /^1[34578]\d{9}$/,//手机
      idcard: /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,//身份证
      num: /^\d*\.?\d+$/,//数字，可包含小数点
      price: /^\d+(\.\d{1,2})?$/,//价格
      bankcard: /^\d{6,25}$/g,//银行卡号
    }
    let errormsg = ''
    if (user_name == '') {
      errormsg = '请输入姓名'
    }
    else if (id_no == '') {
      errormsg = '请输入身份证号'
    }
    // else if (!regMag.idcard.test(id_no)) {
    //   errormsg = '请输入正确的身份证号'
    // }
    else if (bankIndex === '') {
      errormsg = '请选择开户银行'
    }
    else if (linked_acctno == '') {
      errormsg = '请输入银行卡'
    }
    // else if (!regMag.bankcard.test(linked_acctno)) {
    //   errormsg = '请输入正确的银行卡号'
    // }
    else if (reg_phone == '') {
      errormsg = '请输入手机号'
    }
    // else if (!regMag.mobile.test(reg_phone)) {
    //   errormsg = '请输入正确的手机号'
    // }
    else if (occupationIndex === '') {
      errormsg = '请选择职业类型'
    }else if(!cardNoState){
      errormsg = '请上传身份证证件'
    }
    if (errormsg) {
      wx.showToast({
        title: errormsg || '',
        icon: 'none',
      })
      return false
    }
    
    if (timerObj == null) {//计时器实例化
      timerObj = new TimerClass(60, (timeCount, countText) => {
        let disabled = countText !== '获取验证码'
        this.setData({
          timeCount: timeCount,
          disabled: disabled,
          countText: countText,
          isSendMsg: true,
        })
      })
    }
    // 计时器状态
    if (timerObj.disabled) {
      return false
    }
    timerObj.start()
    console.log('sendMsg', params)
    
    // 发送请求
    let {success, msg, data} = await Serv.getAcctApply(params)
    if (!success) {
      timerObj.stop()
      this.setData({isSendMsg: false,})
      wx.showToast({
        title: msg || '',
        icon: 'none',
      })
      return false
    }
    if(success){
      this.setData({ isSendMsg: true, })
    }
    // this.setData({token: data.token || ''})
  },
  
  // 选择银行
  selectBank (e) {
    console.log(e.currentTarget.dataset.index)
    let {bankList = [], showBankList} = this.data
    let {index} = e.currentTarget.dataset
    this.setData({
      bankIndex: index,
      curBankItem: bankList[index],
      showBankList: !showBankList
    })
  },
  goUploadCardNo(){
    let { id_no,user_name } = this.data;
    if(!user_name){
      wx.showToast({title: '请填入姓名',icon: 'none'})
      return false
    }
    if(!id_no){
      wx.showToast({title: '请填入身份证号码', icon: 'none'})
      return false
    }
    wx.navigateTo({
      url:`/subPackages2/pages/wallet/addIdentityCard/addIdentityCard?idCardNo=${id_no}&&name=${user_name}`
    });
  },
  // 选择职业编码
  selectOccupation (e) {
    let {OccupationList = [], showOccupationList} = this.data
    let {index} = e.currentTarget.dataset
    this.setData({
      occupationIndex: index,
      curOccupationItem: OccupationList[index],
      showOccupationList: !showOccupationList
    })
    
  },
  
  // 下一步
  tostep: function (e) {
    // console.log(e.currentTarget.dataset.index)
    let {user_id,verify_code,random_key,password,password_new}=this.data
    let {to} = e.currentTarget.dataset
    // 校验
    let errormsg = ''
    if(to==2){
      if (verify_code == '') {
        errormsg = '请输入手机验证码'
      }
    }
    else if(to==3){

    }
    if (errormsg) {
      wx.showToast({
        title: errormsg || '',
        icon: 'none',
      })
      return false
    }
    
    this.setData({
      step: to
    })
  },
  
  router: function (e) {
    console.log(e)
    console.log(e.currentTarget.dataset.index)
    let to = e.currentTarget.dataset.to
    let url = {cashoutapply: '../cashOutApply/cashOutApply', home: '../index/index'}[to] || ''
    wx.redirectTo({
      url: url
    })
  },
  // 确认验证码
   pswForm:async function (e) {
    let {user_id,verify_code,random_key,password,password_new}=this.data
    let params = {
      user_id,
      verify_code,
      password: password.pwdMw || '',
      random_key: password.randomKey || '',
    }
  // 校验
    let errormsg = ''
    if (password.pwdMw == '') {
      errormsg = '输入交易密码'
    }
    else if (password_new.pwdMw == '') {
      errormsg = '输入确认密码'
    }
    else if (password.pwdHash !== password_new.pwdHash) {
      errormsg = '两次输入密码不一致'
    }
    if (errormsg) {
      wx.showToast({
        title: errormsg || '',
        icon: 'none',
      })
      return false
    }
    //发起请求
    let {data, msg, success} = await Serv.openAcctVerify(params)
    if (!success) {
      wx.showToast({
        title: msg || '',
        icon: 'none',
      })
      this.setData({step: 1})
      console.log(this.data.step)
      return false
    }
    wx.showModal({
      title: '提示',
      content: '操作成功',
      showCancel: false,
      complete: (res)=> {
       this.setData({step: 3})
      }
    })
  },
  // 获取银行卡列表
  banklist: async function (user_id) {
    //发起请求
    let params = { 'product_type': '1', 'pay_chnl': "10" }
    let { success, msg, data = {}, } = await Serv.banklist(params)
    if (!success) {
      wx.showToast({
        title: msg || '',
        icon: 'none',
      })
      return false
    }
    let bankList= data.support_banklist || [];
    bankList.map((item,index)=>{
      item.logourl=`${config.ossHost}images/logo/${item.bank_code}.png`
      
    })
    this.setData({
      bankList: bankList || [],
    })
  },
  
  // 表单输入
  bindinput: function (e) {
    console.log('bindinput', e.currentTarget.dataset, e.detail)
    let label = e.currentTarget.dataset.label
    let value = e.detail.value
    let {cardNoState } = this.data; 

    if(label=='id_no'){
      if(value!=this.data.idCardNo){
        cardNoState = false;
      }else{
        cardNoState = true;
      }
     
    }
    this.setData({
      [label]: value,
      cardNoState
    })
  },
  // 密码控件
  pwdFocus: function (e) {
    // from：当前地址， eventName: 监听定义的事件名
    let label = e.currentTarget.dataset.label
    util.navigateStateChange(this, 'inputDisable')
    wx.navigateTo({
      // from：当前地址， eventName: 监听定义的事件名
      url: '../../pwdCtrl/pwdCtrl?from=/wallet/openWallet/openWallet&eventName=onPwdChange' + `&label=${label}`
    })
    console.log(label)
  },
  //密码控件回调
  pwdCtrlCallback: function () {
  
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let userId = wx.getStorageSync(config.userIdKey)
    this.setData({user_id: userId})
    console.log(this.data.user_id)
    this.banklist()
  
    //监听密码控件输入
    var that = this
    event.on('onPwdChange', that, function (changedData) {
      let {pwdMw = '', label = '', randomKey = '',pwdHash='',pwdlen=0} = changedData
      console.log('DataChanged trigger...', changedData, {
        [label]: pwdMw
      })
      that.setData({
        [label]: {
          pwdMw: pwdMw,
          randomKey: randomKey,
          pwdHash: pwdHash,
          pwdlen: pwdlen,
          pwdMw_new: pwdMw.substr(0,pwdlen),
        },
      })
    })
  },
  /**
   * 判断是否上传身份证
   */
  getIdCardNoState(){
    let cardNoState = false,idCardNo=null;
      Serv.queryIdCardNo().then((res)=>{
          if(res.success&&res.data){
            cardNoState = false;
            idCardNo = res.data.data.idCardNo;
            if(this.data.id_no==res.data.data.idCardNo){
              cardNoState = true;
            }
          }
          this.setData({
            cardNoState:cardNoState,
            idCardNo
            
          })
      })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },
  
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getIdCardNoState();
  },
  
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },
  
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    var that = this
    //取消监听
    event.remove('onPwdChange', that)
  },
  
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },
  
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },
  
  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {
  //
  // }
})
